/* api */
import * as serviceProviderApi from '@src/api/serviceProviderApi';
import { checkButtonDisplayed } from '@src/util/dom';
import ChangeDialog from '@src/modules/serviceProvider/component/ChangeDialog.vue';
import {
  getRoleUser,
  getDelUser,
  resetPwdUpdateAdmin,
  getDepartmentUserCount,
  getBuyAndUseUserNum,
  createAndAddDepartmentUser,
  getBaseLabelList
} from '@src/api/DepartmentApi';
import * as TeamApi from '@src/api/TeamApi';

import { getAdvancedFields } from './fields';
/* enum */
import StorageKeyEnum from '@model/enum/StorageKeyEnum.ts'

// const
import { RoleType,TagType } from '@src/modules/dept/AdvancedType.ts';

import md5 from 'js-md5';
import { storageGet, storageSet } from '@src/util/storageV2.js'; /* enum */
/* components */
import CreateUserPanel from '@src/modules/dept/component/CreateUserPanel.vue';
import {
  isBasicEditionControl,
  isBasicEditionHideEvent,
  isBasicEditionHidePart
} from '@shb-lib/version';
import TeamEditView from '@src/modules/serviceProvider/component/CreateTeamPanel.vue';

import BaseSearchDrawer from 'packages/BaseSearchDrawer';
import BaseSearchPanel from 'packages/BaseSearchPanel';
// 添加外部服务商成员
import ServiceAddMember from '@src/modules/serviceProvider/component/ServiceAddMember.vue';


// img
import { getOssUrl } from '@src/util/assets'
const ontactEmpty = getOssUrl('/no_data.png')
/* export & import */
import { importWechat, importWechatTem, importCellPhone, importCellPhoneTem } from '@src/api/Import';
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum'
/* utils */
import { BaseSelectUserModeEnum } from '@src/component/common/BaseSelectUser'

import _ from 'lodash';
import http from '@src/util/http';
import Page from '@model/Page';
import platform from '@src/platform';
import Platform, { isOpenData, openAccurateTab } from '@src/util/platform.ts';
import tourGuide from '@src/mixins/tourGuide';
import { safeNewDate } from '@src/util/time';
import { getTimestamp, formatDate, objectToUrlParams } from 'pub-bbx-utils'
let export_state;
const pageSizeStorageKey = "serviceProvider_list_pageSize"
export default {
  name: 'department-view',
  inject: ['initData'],
  mixins: [tourGuide],
  data() {
    return {
      isOpenData,
      isButtonDisplayed: checkButtonDisplayed(),
      userDialogVisible: false,
      deptDialogVisible: false,
      showParent: false,
      subDeptExpand: true,
      subDeptKeyword: '',
      isAllotByDept: false,
      nowGuideStep: 5,
      collapse: false,
      collapseLeft: true,
      collapseRight: false,
      deptKeyword: '',
      activeName: 'tag',
      activeName1: 'user',
      roles: [],
      selectedRole: {},
      keyword: '',
      roleKeyword: '',
      roleLoading: false,
      pending: false,
      roleMultipleSelection: [],
      roleParams: {},
      exportDialogvisible: false,
      resetDialogvisible: false,
      resetForm: {
        userId: '',
        pwd: ''
      },

      selectdatetime: '',
      pickerOptions: {
        shortcuts: [
          {
            text: '最近一周',
            onClick(picker) {
              const end = safeNewDate();
              const start = safeNewDate();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', [start, end]);
            }
          },
          {
            text: '最近一个月',
            onClick(picker) {
              const end = safeNewDate();
              const start = safeNewDate();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit('pick', [start, end]);
            }
          },
          {
            text: '最近三个月',
            onClick(picker) {
              const end = safeNewDate();
              const start = safeNewDate();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit('pick', [start, end]);
            }
          },
          {
            text: '最近半年',
            onClick(picker) {
              const end = safeNewDate();
              const start = safeNewDate();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 180);
              picker.$emit('pick', [start, end]);
            }
          },
          {
            text: '最近一年',
            onClick(picker) {
              const end = safeNewDate();
              const start = safeNewDate();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 360);
              picker.$emit('pick', [start, end]);
            }
          }
        ]
      },
      deptInfo: {},
      userRow: '',
      allowCheckDept: false,
      depts: [],
      deptUserCount: {}, // 服务商人员数量统计
      isSeeAllOrg: false, // 是否开始降低组织架构人员可见性开关
      loading: false,
      multipleSelection: [],
      params: {},
      selectedDept: {}, // 选中的服务商
      userPage: new Page(), // 用户列表
      rolePage: new Page(),
      subDepartmentsPage: new Page(),
      userCount: 0, // 已开通账号数量
      accountNum: 0, // 账号总数量
      surplusNum: 0, // 剩余
      addUserForm: {
        userIds: [],
        tagIds: [],
      },
      deptEditId: '',
      isChangeColumn: false,
      columnsList: [],
      quanxian: {},
      isDelete:[],
      currentTabId: '',
      // 高级搜索
      visible: false,
      columnNum: 1,
      advancedColumnNumStorageKey: StorageKeyEnum.RoleListAdvancedColumnNum,
      rolesList: [],
      baseLaberlList: [],
      addMemberVisible: false,
      addMemberFlag: true,
      isSearchDepts: false, // 是否进行了搜索
      importWechat,
      importWechatTem,
      importCellPhone,
      importCellPhoneTem,
      // 存储列表宽度缓存
      tableListForWidthStash:{
        displayName:{width:'180px'},
        loginName:{},
        roleDepartment:{width:'120px'},
        role:{},
        cellPhone:{},
        wechat:{},
        email:{},
        enabled:{},
        workArea:{width:'220px'}
      },
      // 列表缓存标识
      tableStashKey:'serviceProviderRoleList',
      currentRow:{}
    };
  },
  computed: {
    isdele(){
      return this.isDelete.some(x=>x===this.selectedDept.id)
    },
    dialogTitle(){
      return this.deptEditId ? '修改'+(!this.canRemove ? '':'子')+'服务商' : '新建'+(!this.canRemove ? '':'子')+'服务商'
    },
    dialogUserTitle(){
      return this.userRow ? '修改账号' : '新建账号'
    },
    corpId() {
      return this.initData.corpId || '';
    },
    // 0：钉钉端，1：自建，2：企微端
    tenantType() {
      return this.initData.tenantType;
    },
    authorities() {
      return this.initData.authorities || {};
    },
    allowAddUser() {
      return (
        this.authorities.AUTH_STAFF == 3
        && this.authorities.AUTH_ROLE == 3
        && this.authorities.AUTH_TAG == 3
      );
    },
    providerCreate() {
      return 'PROVIDER_CREATE' in this.authorities;
    }, // 新建服务商
    providerDelete() {
      return 'PROVIDER_DELETE' in this.authorities;
    }, // 删除服务商
    providerEdit() {
      return 'PROVIDER_EDIT' in this.authorities;
    }, // 编辑服务商
    providerView() {
      return 'PROVIDER_VIEW' in this.authorities;
    }, // 查看服务商
    // 查看组织架构权限对应之前的团队权限
    hasTagAuth() {
      // 多端默认true
      if (this.tenantType == 1) return true;
      return 'AUTH_TAG' in this.authorities;
    },
    // 账号权限
    hasStaffAuth() {
      // 多端默认true
      if (this.tenantType == 1) return true;
      return 'AUTH_STAFF' in this.authorities;
    },
    // 角色权限
    hasRoleAuth() {
      // 多端默认true
      if (this.tenantType == 1) return true;
      return 'AUTH_ROLE' in this.authorities;
    },
    // 是否账号管理权限
    isAuthStaff(){
      return 'AUTH_STAFF' in this.authorities;
    },

    teamLeadersName() {
      return (
        this.deptInfo.serviceProviderManager
        && this.deptInfo.serviceProviderManager
          .map(i => (i && i.displayName) || '')
          .join('，')
      );
    },

    canRemove() {
      // 主服务商下面成员不能移除
      return this.selectedDept.parentId;
    },
    // 是否在钉钉环境
    isDingTalk() {
      return Platform.isDingTalk();
    },
    productV2Gray() {
      return this.initData.openSuperCodePro;
    },
    isBasicEditionControl() {
      return isBasicEditionControl();
    },
    // 基础版隐藏事件
    isBasicEditionHideEvent() {
      return isBasicEditionHideEvent();
    },
    // 基础版隐藏备件
    isBasicEditionHidePart() {
      return isBasicEditionHidePart();
    },
    // 高级搜索字段
    fields() {
      let f = {};
      return getAdvancedFields(this)
        .map(field => {
          f = _.cloneDeep(field);
          let formType = f.formType;

          if (f.displayName === '所属部门') {
            formType = 'tags';
          }

          return Object.freeze({
            ...f,
            isNull: 1,
            formType,
            originalFormType: f.formType,
          })
        })
        .sort((a, b) => a.orderId - b.orderId)
        .filter( x => this.canRemove ? x.fieldName !== 'tags' : x );
    },
    ontactEmptyImg(){
      return ontactEmpty;
    },
    // 当前账号是否存在服务商部门
    isProviderSign(){
      return sessionStorage.getItem('isProviderSign') == 1;
    }
  },
  watch:{
    activeName1(newVal, oldVal){
      this.$nextTick(()=>{
        this.buildColumn()
      })
    }
  },
  async created() {
    await this.getCol();
  },
  mounted() {
    this.currentTabId = window.frameElement.dataset.id;
    // isAllotByDept对应钉钉端是否按照钉钉通讯录选人 如果钉钉端之前勾选了按服务团队派单isAllotByDept为false,
    // 去掉引导页面
    if (this.tenantType == 0) {
      // 钉钉端
      this.isAllotByDept = !this.initData.allotByTag;
    }
    // 读取列表的分页缓存数据
    let pageSizeStash = storageGet(pageSizeStorageKey) || '';
    pageSizeStash = pageSizeStash ? JSON.parse(pageSizeStash) : {};
    if(pageSizeStash.hasOwnProperty('user')){
      this.params['pageSize'] = pageSizeStash.user;
    }
    if(pageSizeStash.hasOwnProperty('dept')){
      this.subDepartmentsPage['pageSize'] = pageSizeStash.dept;
    } 
    this.buildColumn();
    this.initialize();
    this.getUserTag()
    this.$eventBus.$on('submit' , this.userAdd)
  },
  methods: {
    openChangeDialog(row){
      console.log(row)
      this.currentRow = row
      this.$refs.changeDialog.openDialog()
    },
    getUserTag(){
      serviceProviderApi.userTag().then(r=>{
        if(r.status == 0)
         this.isDelete = r.data
      })
    },
    userDialogSubmit() {
      this.$refs.createUserPanel.validate();
    },
    getCol() {
      if (this.getStroge()) {
        this.columnsList = JSON.parse(this.getStroge());
      } else {
        this.columnsList = this.columns();
      }
    },
    /**
     * @description 修改选择列设置
     * @param {Object} event 事件对象
     */
    async saveColumnStatus(event) {
      let columns = event.data || [];
      localStorage.setItem('serviceProvider', JSON.stringify(columns));
      this.getCol();
    },
    getStroge() {
      return localStorage.getItem('serviceProvider') || null;
    },
    changeCol() {
      // window.TDAPP.onEvent('pc：服务商管理-选择列事件');
      this.$refs.advanced.open(this.columnsList);
    },
    columns() {
      return [
        {
          label: '服务商名称',
          displayName: '服务商名称',
          fieldName: 'serviceProviderName',
          field: 'serviceProviderName',
          show: true,
          fixed: true,
          isSystem: true,
          tableName: 'serviceProvider',
          minWidth: '150px'
        },
        {
          label: '社会统一信用代码',
          displayName: '社会统一信用代码',
          fieldName: 'creditCode',
          field: 'creditCode',
          tableName: 'serviceProvider',
          isSystem: true,
          fixed: true,
          show: true
        },
        {
          label: '服务商属性',
          displayName: '服务商属性',
          fieldName: 'serviceProviderAttribute',
          field: 'serviceProviderAttribute',
          tableName: 'serviceProvider',
          isSystem: true,
          fixed: true,
          show: true
        },
        {
          value: 'registerCompanyName',
          label: '注册公司名称',
          displayName: '注册公司名称',
          fieldName: 'registerCompanyName',
          field: 'registerCompanyName',
          tableName: 'serviceProvider',
          isSystem: true,
          fixed: true,
          show: true
        },
        {
          value: 'serviceProviderManager',
          label: '服务商主管',
          displayName: '服务商主管',
          fieldName: 'serviceProviderManager',
          field: 'serviceProviderManager',
          tableName: 'serviceProvider',
          isSystem: true,
          fixed: true,
          show: true
        },
        {
          value: 'linkPhone',
          label: '电话',
          displayName: '电话',
          fieldName: 'linkPhone',
          field: 'linkPhone',
          tableName: 'serviceProvider',
          isSystem: true,
          fixed: true,
          show: true
        },
        {
          value: 'wechat',
          label: '微信',
          displayName: '微信',
          fieldName: 'wechat',
          field: 'wechat',
          tableName: 'serviceProvider',
          isSystem: true,
          fixed: true,
          show: true
        },
        {
          value: 'email',
          label: '邮箱',
          displayName: '邮箱',
          fieldName: 'email',
          field: 'email',
          tableName: 'serviceProvider',
          isSystem: true,
          fixed: true,
          show: true
        },
        {
          value: 'legalPerson',
          label: '法人代表',
          displayName: '法人代表',
          fieldName: 'legalPerson',
          field: 'legalPerson',
          tableName: 'serviceProvider',
          isSystem: true,
          fixed: true,
          show: true
        },
        {
          value: 'tagPlaceList',
          label: '注册地址',
          displayName: '注册地址',
          fieldName: 'tagPlaceList',
          field: 'tagPlaceList',
          tableName: 'serviceProvider',
          isSystem: true,
          fixed: true,
          show: true
        },
        {
          value: 'label',
          label: '标签',
          displayName: '标签',
          fieldName: 'label',
          field: 'label',
          tableName: 'serviceProvider',
          isSystem: true,
          fixed: true,
          show: true
        }
      ];
    },
    addAdmin() {
      // this.$platform.openTab({
      //   id: 'serviceProviderView_home',
      //   title: '服务商主页',
      //   close: true,
      //   url: `/security/tag/serviceProviderHome/${this.selectedDept.serviceProviderTenantId}?parentTab=${this.currentTabId}`
      // });
      openAccurateTab({
        type: PageRoutesTypeEnum.PageServiceProviderViewHome,
        key: this.selectedDept.serviceProviderTenantId,
        params: `parentTab=${this.currentTabId}`,
      })
    },
    ChildTagList(name) {
      if (name) {
        this.subDepartmentsPage.keyword = name;
      } else {
        delete this.subDepartmentsPage.keyword;
      }
      if (!this.subDepartmentsPage.pageSize) {
        this.subDepartmentsPage.pageSize = 10;
      }
      if (this.subDepartmentsPage.pageNum == 1) {
        this.subDepartmentsPage.list = [];
      }
      this.subDepartmentsPage.parentId = this.selectedDept.id;
      let res = serviceProviderApi.list(this.subDepartmentsPage);
      return res.then(deptList => {
        this.loading = false
        this.subDepartmentsPage.merge(Page.as(deptList.data));
      });
    },
    submit() {
      this.$refs.team.submit(params => {
        if (!params.parentId) {
          params.parentId = this.selectedDept.id;
          serviceProviderApi.create(params).then(r => {
            this.$platform.notification({
              title: !r.status ? '成功' : '失败',
              message: !r.status ? '创建成功' : r.message,
              type: !r.status ? 'success' : 'error'
            });
            this.submitAddDept();
          });
        } else {
          serviceProviderApi.edit(params).then(r => {
            this.$platform.notification({
              title: !r.status ? '成功' : '失败',
              message: !r.status ? '修改成功' : r.message,
              type: !r.status ? 'success' : 'error'
            });
            this.submitAddDept();

            // 更新主页内容 TO DO refreshTab 做标准化
            this.$platform.refreshTab('serviceProviderView_home');
          });
        }
      });
    },
    submitAddDept() {
      this.deptDialogVisible = false;
      this.initialize(false);
    },

    /* 打开服务电话弹出框 */
    openTelDialog() {
      this.$refs.serviceTelModal.open();
    },
    openWxDialog() {
      this.$refs.serviceWxModal.open();
    },
    subDeptSearch: _.debounce(function(e) {
      // 下级服务商模糊搜索
      this.subDepartmentsPage.pageNum = 1;
      this.subDepartmentsPage.pageSize = 10;
      this.ChildTagList(e);
    }, 500),

    btnCollapse(dir) {
      if (dir === 'left') {
        this.collapse = true;
        this.collapseLeft = !this.collapseLeft;
        this.collapseRight = true;
      } else {
        this.collapse = false;
        this.collapseRight = !this.collapseRight;
        this.collapseLeft = true;
      }
    },
    debounce: _.debounce(async function() {
      this.isSearchDepts = true;
      // 服务商模糊搜索
      try {
        this.depts = await this.fetchDept();
        if(this.depts[0]) this.initDeptUser(this.depts[0]);
      } catch (error) {
        console.log(error);
        this.loading = false;
      }
    }, 1000),
    toggleEnable(row) {
      row.pending = true;
      this.$http
        .post('/security/user/enable', { userId: row.userId }, false)
        .then(res => {
          row.pending = false;
          if (res.status) return this.$platform.alert(res.message);
          this.initialize(false);
        })
        .catch(err => {
          row.pending = false;
          console.error('toggleStatus catch err', err);
        });
    },
    async deleteDeptUser(row) {
      if (
        await this.$platform.confirm(
          '确定要把选中成员删除吗？删除后将清空账号的角色信息'
        )
      ) {
        row.pending = true;
        this.$http
          .post('/security/user/delete', { userId: row.userId }, false)
          .then(res => {
            row.pending = false;
            if (res.status) return this.$platform.alert(res.message);
            this.initialize(false);
          })
          .catch(err => {
            row.pending = false;
            console.error('toggleStatus catch err', err);
          });
      }
    },

    // 导出动态
    exportFeed(type) {
      if (!type && !this.multipleSelection.length)
        return this.$platform.alert('请至少选择一个用户！');
      export_state = type;
      this.exportDialogvisible = true;
    },
    // 导出账号
    exportAccount(type) {
      if (!type && !this.multipleSelection.length)
        return this.$platform.alert('请至少选择一个用户！');
      export_state = type;
      if (export_state === 'all') {
        // 导出全部
        window.location.href = !this.selectedDept.parentId
          ? '/security/user/tag/exportBatch'
          : `/security/user/tag/exportBatch?tagId=${this.selectedDept.id}`;
      } else {
        // 导出选中的
        let ids = [];
        for (const user of this.multipleSelection) {
          ids.push(user.userId);
        }
        // ids = ids.join(',');
        const params = {
          userIdList : ids
        }
        let date = formatDate(safeNewDate(), 'YYYY-MM-DD');
        let fileName = `${date}${this.$t('department.tips.memberMessage')}.xlsx`;
        this.$http.post('/security/user/tag/exportBatch/new', params, true, {responseType: 'blob'})
          .then(blob => {
            let link = document.createElement('a');
            let url = URL.createObjectURL(blob);
            link.download = fileName;
            link.href = url;
            this.$refs.bridge.appendChild(link);
            link.click();
            setTimeout(() => {
              URL.revokeObjectURL(url);
              this.$refs.bridge.removeChild(link);
            }, 150);
          })
          .catch(err => console.error(err));
        // window.location.href = `/security/user/tag/exportBatch?userIdsStr=${ids}`;
      }
      export_state = '';
    },
    exportData() {
      const api = '/security/user/workState/exportBatch/new';
      
      const [timeStart = '', timeEnd = ''] = this.selectdatetime || []
      const params = {
        timeStart: timeStart ? formatDate(timeStart) : '', // 旧数据确保是时间字符串
        timeEnd: timeEnd ? formatDate(timeEnd) : '', // 旧数据确保是时间字符串
        timeStartDate: getTimestamp(timeStart), // 国际化时间新增时间戳参数
        timeEndDate: getTimestamp(timeEnd), // 国际化时间新增时间戳参数
      }

      if (export_state === 'all') {
        // 导出全部
        params.tagId = this.selectedDept?.id
        window.location.href = `${api}?${objectToUrlParams(params)}`;
      } else {
        // 导出选中的
        params.userIdsStr = (this.multipleSelection || []).map(item => item.userId).join(',')
        let date = formatDate(safeNewDate(), 'YYYY-MM-DD');
        let fileName = `${date}${this.$t('department.tips.memberMessage')}.xlsx`;
        this.$http.post(api, params, true, {responseType: 'blob'})
          .then(blob => {
            let link = document.createElement('a');
            let url = URL.createObjectURL(blob);
            link.download = fileName;
            link.href = url;
            this.$refs.bridge.appendChild(link);
            link.click();
            setTimeout(() => {
              URL.revokeObjectURL(url);
              this.$refs.bridge.removeChild(link);
            }, 150);
          })
          .catch(err => console.error(err));
      }
      export_state = '';
      this.selectionToggle();
      this.exportDialogClosed();
    },
    exportDialogClosed() {
      this.selectdatetime = '';
      this.exportDialogvisible = false;
    },
    userResetPwdConfirm(userId) {
      this.resetDialogvisible = true;
      this.resetForm.userId = userId;
    },
    resetDialogClosed() {
      this.resetForm.userId = '';
      this.resetForm.pwd = '';
      this.resetDialogvisible = false;
    },

    async resume(userId) {
      try {
        if (await this.$platform.confirm('确定要恢复该账号吗？')) {
          const { status, message } = await http.post(
            '/security/user/resume',
            { userId },
            false
          );
          // if(status !== 0) this.$message.error(message || '');
          let isSucc = status == 0;
          this.$platform.notification({
            title: isSucc ? '成功' : '失败',
            message: isSucc ? '账号恢复成功' : message,
            type: isSucc ? 'success' : 'error'
          });
          isSucc && this.chooseRole(this.selectedRole);
        }
      } catch (error) {
        console.error(error);
      }
    },
    createTransTab(type, userId) {
      let fromId = window.frameElement.getAttribute('id');
      // this.$platform.openTab({
      //   id: 'M_JOBTRANSFER_DETAIL',
      //   title: '转交详情',
      //   close: true,
      //   url: `/jobtransfer/view?type=${type}&userId=${userId}`,
      //   fromId
      // });
      openAccurateTab({
        type: PageRoutesTypeEnum.PageJobtransferView,
        params: `type=${type}&userId=${userId}`,
        fromId
      })
    },
    async resetUserPwd() {
      if (!this.resetForm.pwd) return this.$platform.alert('重置密码不能为空');
      if (this.resetForm.pwd.length < 6) return this.$platform.alert('密码长度不能低于 6 位');
      let params = {};
      params.userId = this.resetForm.userId;
      params.password = md5(this.resetForm.pwd);
      resetPwdUpdateAdmin(params)
        .then(result => {
          let isSucc = result.status == 0;
          this.$platform.notification({
            title: isSucc ? '成功' : '失败',
            message: isSucc ? '密码重置成功' : result.message,
            type: isSucc ? 'success' : 'error'
          });
          if (isSucc) this.resetDialogClosed();
        })
        .catch(err => console.log(err));
    },

    search() {
      // 组织架构人员搜索
      this.initDeptUser(this.selectedDept);
    },
    searchRole() {
      // 角色人员搜索
      this.rolePage.list = [];
      this.chooseRole(this.selectedRole);
    },
    chooseDelRole() {
      this.activeName = 'role';
      this.selectedDept = {};
      this.rolePage.list = [];
      let role = { id: -1, text: '已删除账号' };
      this.chooseRole(role);
    },
    async chooseRole(role) {
      this.multipleSelection = [];
      this.roleMultipleSelection = [];
      if (this.selectedRole.id != role.id) {
        this.roleKeyword = '';
      }
      this.selectedRole = role;
      this.roleLoading = true;
      // 获取角色下面的人员
      this.roleParams.keyword = this.roleKeyword;
      this.roleParams.roleId = '';
      this.roleParams.roleType = '';
      this.roleParams.pageNum = 1;
      this.roleParams.type = 1
      this.rolePage.list = [];
      if (role.id == 0) {
        // 待分配账号
        this.roleParams.roleType = 'noauth';
        this.getBuyAndUseUserNumData(); // 已开通账号数量
      } else if (role.id == -1) {
        // 已删除账号
        this.roleParams.roleType = 'delauth';
      } else {
        this.roleParams.roleId = role.id;
      }
      return this.getRoleUserList(this.roleParams)
        .then(rolePage => {
          this.rolePage.merge(Page.as(rolePage));
        })
        .catch(err => console.error('err', err))
        .finally(() => (this.roleLoading = false));
    },

    getRoleUserList(params) {
      if (this.selectedRole.id == -1) return getDelUser(params);
      return getRoleUser(params);
    },
    getBuyAndUseUserNumData() {
      getBuyAndUseUserNum()
        .then(result => {
          let data = result.data || {};
          this.userCount = data.userCount || 0; // 已开通账号数量
          this.accountNum = data.accountNum || 0; // 账号总数量
          this.surplusNum = Number(data.accountNum) - Number(data.userCount) || 0;
        })
        .catch(err => console.log(err));
    },
    handleClick(tab, event) {
      if (tab.name === 'role') {
        this.chooseRole(this.selectedRole);
      }
    },
    handleClick1(tab, event) {
      if (tab.name === 'user') {
        this.params.pageNum = 1;
        // 请求成员信息
        this.fetchUser().finally(() => (this.loading = false));
      } else {
        // 请求下级服务商信息
        this.ChildTagList();
      }
    },
    addDepartment(br) {
      if (br) {
        this.showParent = true;
      } else {
        this.showParent = false;
      }
      this.deptEditId = 0;
      this.deptDialogVisible = true;
    },
    async delDepartment(id) {
      // 您删除的团队，如果包含子团队将会一并删除，是否继续？
      try {
        const isChildren = this.selectedDept.children?.length > 0;
        if (
          await this.$platform.confirm(
            isChildren ? '您删除的部门，如果有子部门，也将一并删除，是否继续删除?' :
            '服务商删除后，服务商下的账号将会在外部服务商下显示；为保证账号的正常使用，请尽快分配新的部门'
          )
        ) {
          let ids = [this.selectedDept.serviceProviderTenantId];
          if (id) ids = [id];

          let result = await serviceProviderApi.serviceProviderDelete(ids);

          this.$platform.notification({
            type: result.status == 0 ? 'success' : 'error',
            title: `服务商删除${result.status == 0 ? '成功' : '失败'}`,
            message: result.status == 0 ? null : result.message
          });

          if (result.status == 0) {
            this.initialize(true);
          }
        }
      } catch (e) {
        console.error('teamDelete catch error', e);
      }
    },

    /** 选择服务商 */
    chooseDept(event) {
      console.log('chooseDept event');
      let { node, value } = event;
    },
    chooseUser(type) {
      let options = {
        title: '请选择成员',
        seeAllOrg: true,
        max: -1,
        selectedUsers: this.userPage.list,
        typeServiceProvider: 1,
        mountEl: this.$el,
        mode: BaseSelectUserModeEnum.Filter
      };

      this.$fast.select.multi.user(options)
        .then(result => {
          // console.log(result);
          if (result.status == 0) {
            let data = result.data || {};
            if (data.users.length) {
              this.addUserForm.userIds = data.users.map(r => r.userId);
              this.changeRoleSubmit();
            }
          }
        })
        .catch(err => console.error(err));
    },
    changeRoleSubmit() {
      this.addUserForm.tagIds = [this.selectedDept.id];
      serviceProviderApi.bindUser(this.addUserForm).then(r => {
        this.$platform.notification({
          title: r.status === 0 ? '分配成功' : '分配失败',
          message: r.status === 0 ? '分配成功' : r.message,
          type: r.status === 0 ? 'success' : 'error'
        });
        if(r.status !== 0) return;

        this.addUserForm.isChangeRole = false;
        this.initialize(false);
      });
    },
    /** 抓取服务商数据 */
    fetchDept() {
      let params = {
        seeAllOrg: this.isSeeAllOrg,
        keyword: this.deptKeyword
      };

      return serviceProviderApi
        .tree(params)
        .then(result => {
          return (result && result.data) || [];
        })
        .catch(err => console.error('err', err));
    },
    /* 抓取服务商 人员数量 */
    fetchDeptCount() {
      return getDepartmentUserCount();
    },
    /** 抓取用户数据 */
    fetchUser() {
      let params = this.params;
      if (params.pageNum == 1) {
        this.userPage.list = [];
      }
      params.tagId = this.selectedDept.serviceProviderTenantId || this.selectedDept.parentId ? this.selectedDept.id : '';
      params.type = this.selectedDept.type || '';

      return TeamApi.userList({
        ...params,
        ...this.buildSearchParams()
      })
        .then(userPage => {
          
          this.userPage.merge(Page.as(userPage));
        })
        .catch(err => console.error('err', err));
    },
    /* 查询是否开启 降低组织架构的开关 */
    getSeeAllOrg() {
      return http.post('/setting/user/getSeeAllOrg').then(result => {
        return result;
      });
    },
    /* 跳转 用户详情页 */
    goUserDetail(id) {
      if (!window.frameElement) return;

      let fromId = window.frameElement.getAttribute('id');
      // this.$platform.openTab({
      //   id: `tab_department_view_${id}`,
      //   title: '成员详情',
      //   close: true,
      //   reload: true,
      //   url: `/security/user/view/${id}?from=department`,
      //   fromId
      // });
      openAccurateTab({
        type: PageRoutesTypeEnum.PageSecurityUserView,
        key: id,
        params: 'from=department',
        reload: true,
        fromId
      })
    },

    handleSizeChange(pageSize) {
      this.params.pageSize = pageSize;
      this.params.pageNum = 1;

      this.userPage.list = [];

      this.loading = true;
      let stash_data = storageGet(pageSizeStorageKey) || '';
      stash_data = stash_data ? JSON.parse(stash_data) : {};
      storageSet(pageSizeStorageKey, JSON.stringify({ ...stash_data,
        [this.activeName1]:pageSize
      }))

      this.fetchUser().finally(() => (this.loading = false));
    },
    depthandleSizeChange(pageSize) {
      this.subDepartmentsPage.pageSize = pageSize;
      this.subDepartmentsPage.pageNum = 1;
      this.subDepartmentsPage.list = [];
      this.loading = true;
      let stash_data = storageGet(pageSizeStorageKey) || '';
      stash_data = stash_data ? JSON.parse(stash_data) : {};
      storageSet(pageSizeStorageKey, JSON.stringify({ ...stash_data,
        [this.activeName1]:pageSize
      }))
      this.ChildTagList().finally(() => (this.loading = false));
    },
    roleHandleSizeChange(pageSize) {
      this.roleParams.pageSize = pageSize;
      this.roleParams.pageNum = 1;

      this.rolePage.list = [];

      this.roleLoading = true;

      // this.fetchUser().finally(() => this.loading = false);
      return this.getRoleUserList(this.roleParams)
        .then(rolePage => {
          this.rolePage.merge(Page.as(rolePage));
        })
        .catch(err => console.error('err', err))
        .finally(() => (this.roleLoading = false));
    },
    /** 初始化 */
    initialize(isInit = true) {
      this.initializeDept(isInit);
    },
    /** 初始化服务商数据 */
    async initializeDept(isInit = true) {
      this.loading = true;
      this.isSeeAllOrg = false;

      try {
        /* 如果开启 查询按组织架构选项 */
        let result = await this.getSeeAllOrg();
        this.isSeeAllOrg = result.data;
      } catch (error) {
        console.log('error: ', error);
      }

      let subtask = [this.fetchDept(), this.fetchDeptCount()];

      Promise.all(subtask)
        .then(result => {
          let depts = result[0] || [];
          let deptUserCount = result[1] || {};

          this.deptUserCount = deptUserCount.data || {};
          if(depts && depts.length > 0 && !depts[0].children){
            depts[0].children = [];
          }
          this.depts = depts;
          this.initDeptUser(
            isInit ? this.depts[0] : _.cloneDeep(this.selectedDept)
          );
        })
        .catch(err => console.error(err));
    },
    /** 选中一个服务商 */
    async initDeptUser(dept) {
      this.loading = true
      this.subDeptKeyword = '';
      this.activeName = 'tag';
      this.multipleSelection = [];
      this.roleMultipleSelection = [];
      if (this.activeName == 'tag' && this.selectedRole.id == -1) {
        this.selectedRole = { id: '0', text: '待分配人员' };
      }
      try {
        if (this.selectedDept.serviceProviderId != dept.serviceProviderId) {
          this.keyword = '';
        }
        this.selectedDept = dept;
        this.subDepartmentsPage.pageNum = 1;
        this.userPage.list = [];
        // 查询用户
        this.params.keyword = this.keyword;
        // 只有选择的不是主tag 搜索人员就不传tagid 后端返回主tag的parentId为null
        if (dept.parentId) {
          this.params.id = dept.serviceProviderId || dept.serviceProviderId;
        } else {
          this.params.id = '';
        }
        // this.params.departmentId = dept.id;
        this.params.pageNum = 1;
        this.params.seeAllOrg = this.isSeeAllOrg;
        this.fetchTeamData();
        await this.handleClick1({ name: this.activeName1 });
      } catch (error) {
        console.error(error);
        this.loading = false;
      }

    },
    // 查询详情
    async fetchTeamData() {
      if (!this.selectedDept.serviceProviderId && !this.selectedDept.serviceProviderTenantId) return;
      try {
        let result = await serviceProviderApi.info({
          id: this.selectedDept.serviceProviderId || this.selectedDept.serviceProviderTenantId
        });
        if (result.status) {
          this.deptInfo = {};
          return this.$platform.notification({
            title: '失败',
            message: result.message,
            type: 'error'
          });
        }
        if (result.data) {
          this.deptInfo = result.data;
          this.subDepartments = this.deptInfo.children || [];
        }

        // this.subDepartments.merge(Page.as(result));
      } catch (error) {
        console.log('error: ', error);
      }
    },
    isRootDepartment(department = {}) {
      return this.depts.some(dept => dept.id == department.id);
    },
    jump(pageNum) {
      this.params.pageNum = pageNum;

      this.userPage.list = [];

      this.loading = true;

      this.fetchUser().finally(() => (this.loading = false));
    },
    deptjump(pageNum) {
      this.subDepartmentsPage.pageNum = pageNum;
      this.subDepartmentsPage.list = [];
      this.loading = true;

      this.ChildTagList().finally(() => (this.loading = false));
    },
    roleJump(pageNum) {
      this.roleParams.pageNum = pageNum;

      this.rolePage.list = [];

      this.roleLoading = true;

      return this.getRoleUserList(this.roleParams)
        .then(rolePage => {
          this.rolePage.merge(Page.as(rolePage));
        })
        .catch(err => console.error('err', err))
        .finally(() => (this.roleLoading = false));
    },
    nodeRender(h, node) {
      let content = (
        <span>
          {node.tagName}（{node.userCount || 0}）
        </span>
      );

      let count = this.deptUserCount[node.id] || 0;
      if (count <= 0) return content;

      return (
        <div class="dept-node-wrap">
          <span class="dept-node-name">{node.tagName}</span>
          <span class="dept-node-count">&nbsp;({count})人</span>
        </div>
      );
    },
    openCreateUserPanel(row) {
      if (row) {
        let obj = JSON.parse(JSON.stringify(row));
        obj.dateTime = safeNewDate().getTime();
        this.userRow = row ? JSON.stringify(obj) : '';
      }else{
        this.userRow = ''

        setTimeout(()=>{
          this.$refs.createUserPanel.form.tagList = [this.selectedDept];
        },0)
      }
      this.userDialogVisible = true;
      // this.$refs.createUserPanel.open({});
    },
    openDepartmentEditPanel(row) {
      if(!row.serviceProviderId && !row.serviceProviderTenantId) return;
      this.deptEditId = row.serviceProviderId || row.serviceProviderTenantId;
      this.showParent = false;
      this.deptDialogVisible = true;
      this.$refs.team.initKeyVal();
    },
    /** select dept person */
    selectionHandle(selection) {
      this.multipleSelection = selection.slice();
    },
    selectionToggle(rows) {
      if (rows) {
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
        this.multipleSelection = [];
      }
    },
    /** select role person */
    roleSelectionHandle(selection) {
      this.roleMultipleSelection = selection.slice();
    },

    async userDeleteConfirm(type) {
      // 批量删除
      if (type === 'multiple' && this.multipleSelection.length <= 0) {
        return this.$platform.alert('请先选择需要移除的成员');
      }

      if (
        await this.$platform.confirm('确定要把选中成员从该服务商中移除吗？')
      ) {
        this.userDelete();
      }
    },
    userDelete() {
      let params = {
        userIds: this.multipleSelection.map(item => item.userId).join(','),
        tagId: this.selectedDept.id
      };

      this.loading = true;

      TeamApi.deleteUser(params)
        .then(result => {
          let isSucc = result.status == 0;

          if (isSucc) {
            this.initialize(false);
            if(!this.deptDialogVisible) this.deptEditId = '';
          }

          this.$platform.notification({
            title: isSucc ? '成功' : '失败',
            message: isSucc ? '移除成功' : result.message,
            type: isSucc ? 'success' : 'error'
          });
        })
        .catch(err => console.log(err))
        .finally(() => (this.loading = false));
    },
    userAdd(form = {}) {
      let params = JSON.parse(JSON.stringify(form));
      if(!params.userId)
        params.loginPassword = md5(params.pass);
      params.roles = params.role.map(r => ({ id: r })) || [];

      this.loading = true;

      createAndAddDepartmentUser(params)
        .then(result => {
          let isSucc = result.status == 0;

          if (isSucc) {
            this.userDialogVisible = false;
            // this.$refs.createUserPanel.close();
            this.initialize(false);
          }

          this.$platform.notification({
            title: isSucc ? '成功' : '失败',
            message: isSucc ? '添加成功' : result.message,
            type: isSucc ? 'success' : 'error'
          });
        })
        .catch(err => console.log(err))
        .finally(() => (this.loading = false));
    },
    // 帮助文档
    openHelpDoc() {
      let url = ''
      if(this.tenantType == 2) {
        url = 'https://docs.qq.com/doc/p/2cec0fde98fc3e19274e129ae3806db7de08a065?dver=2.1.27237808'
      } else if(this.tenantType == 4) {
        url = 'https://publink-hz.feishu.cn/wiki/wikcnUYQrZg1Kc1d0L9TB1Shjz3'
      } else {
        url = 'https://doc.shb.ltd/shb_xoqazk/ia4qctp2ly559d1m/br34li8lnnceroyp/yugh4uyttozl4210.html'
      }
      platform.openLink(url);
    },
    // 构建搜索参数
    buildSearchParams() {
      let advancedSearchParams = this.$refs.searchPanel ? this.$refs.searchPanel.buildParams() : {};
      
      const {tags, roleIds, enabled, labelIds} = advancedSearchParams;
      const tagIdsStr = tags?.map(x=>x.id);
      
      return {
        ...this.params,
        roleIds: roleIds?.filter(x=>x!==RoleType)?.join(','),
        tagIds: tagIdsStr?.filter(x=>x!==TagType)?.join(','),
        enabled: enabled ? Number(enabled) : '',
        labelIds: labelIds?.join(','),
        advancedSearchRoleType: roleIds?.some(x=>x===RoleType),
        advancedSearchTagType: tagIdsStr?.some(x=>x===TagType)
      }
    },
    // 高级搜索
    panelSearchAdvancedToggle() {
      this.getRoleListData();
      this.getBaseLabelList();
      this.visible = true;
    },
    // 设置高级搜索展示列数
    setAdvanceSearchColumn(command) {
      this.columnNum = Number(command);
    },
    // 重置
    resetParams() {
      window.location.reload()
    },
    // 获取角色列表
    getRoleListData(){
      serviceProviderApi.getRoleTree()
        .then( result => {
          if(!result||!result.data||!result.data.children||result.data.children.length<2)
            return false
          
          if(result.data.children[1].type === 'assigned'){
            let roles = result.data.children[1].children;
            this.rolesList = roles.map(role => ({ text: role.roleName, value: role.roleId }));
            this.rolesList.unshift({ text: '无', value: RoleType })
          }
        })
        .catch((err) => console.error(err));
    },
    // 获取标签数据
    getBaseLabelList(){
      getBaseLabelList().then(res=>{
        const { status,data,message } = res;
        if(status !== 0) return;

        this.baseLaberlList = data.map(x=>({text: x.tagName,value: x.id}));
      })
    },
    // 添加服务商成员按钮
    async addServiceMember(flag){
      if(!flag && !this.multipleSelection.length)
        return this.$platform.alert('请至少选择一个用户！');

      this.addMemberVisible = true;
      this.addMemberFlag = flag;
    },
    // 添加操作
    addMemberSubmit(){
      if(this.addMemberFlag){
        this.$refs.serviceAddForm.addMemberSubmit();
      }else {
        const ids = this.multipleSelection.map(x => x.userId);
        this.$refs.serviceAddForm.addMemberSubmit(ids);
      }
    },
    // 提交成功
    succSubmit(){
      this.addMemberVisible = false;

      this.initialize();
      this.getRoleListData();
    },

    /**
     * @des 表单拖拽钩子函数
     */
    headerDragend(newWidth, oldWidth, column, event) {
      let stash_data = storageGet('notStandardTableStash') || '';
      stash_data = (stash_data && JSON.parse(stash_data)) || {};
      if(this.activeName1 == 'dept'){
        let baseList = _.cloneDeep(this.columnsList)
        baseList = baseList.map(i => ({field:i.field, width:i.field == column.property ? `${column.width}px` : i.width || ''})).reduce((acc, col) => (acc[col.field] = col) && acc, {});
        stash_data[`${this.tableStashKey}${this.activeName1}`] = baseList
      }else {
        this.$set(this.tableListForWidthStash, column.property, {width:`${column.width}px`});
        stash_data[`${this.tableStashKey}${this.activeName1}`] = this.tableListForWidthStash
      }
      
      storageSet('notStandardTableStash', JSON.stringify(stash_data));
    },
    /**
     * @des 初始化表格宽度函数
     */
    buildColumn(){
      try {
        let stash_data = storageGet('notStandardTableStash');
        stash_data = stash_data && JSON.parse(stash_data);
        let pageStash = stash_data[`${this.tableStashKey}${this.activeName1}`] || {};
        if(this.activeName1 == 'dept'){
          this.columnsList.map(item=>{
            if(pageStash.hasOwnProperty(item.field)){
              item['width'] = pageStash[item.field].width
            }
            return item
          })
        }else {
          this.$set(this, 'tableListForWidthStash', {...this.tableListForWidthStash, ...pageStash});
        }
        
      } catch (error) {
        console.warn(error, 'error try catch');
      }

    }
  },
  components: {
    [CreateUserPanel.name]: CreateUserPanel,
    [TeamEditView.name]: TeamEditView,
    [BaseSearchDrawer.name]: BaseSearchDrawer,
    [BaseSearchPanel.name]: BaseSearchPanel,
    [ServiceAddMember.name]: ServiceAddMember,
    [ChangeDialog.name]: ChangeDialog,
  }
};